<template>
	<div id="show" :class="this.$store.getters.isIphoneX ? 'pad-top80' : 'pad-top'">
		<back-header title="梦想抓娃娃"></back-header>
		<div class="catchblock">
			<div class="show_video">
				<div class="onlines">
					<div class="onlinenum">
						<span class="onlinenumber">{{onlineNum}}人在房间</span>
					</div>
					<ul class="onlineuser elip">
						<li class="onlineitem" v-for="item in onnlineList" :data-uid="item.user_id" @click="goUserecord(item.user_id)">
							<img :src="item.avatar" :class=" 'userid'+item.user_id ">
						</li>
					</ul>
				</div>
				<div class="chat-msg-box" id="upchat_hall">
					<div class="live-msg-list clearfix" id="chat_hall">
						<div class="msg" v-for="item in chatMsg">
							<p v-if="item.type == 1" style="color:rgb(243, 242, 239);background:rgba(131, 115, 203, 0.79);"><span>{{item.nickname}}:</span>{{item.content}}</p>
							<p v-else-if="item.type == 2" style="color:#f0dc07;background:rgba(131, 115, 203, 0.79);"><span>{{item.nickname}}:</span>{{item.content}}</p>
							<p v-else-if="item.type == 3" style="color:rgb(240, 240, 237);background:rgba(254, 107, 44, 0.78);">{{item.content}}</p>
							<p v-else style="color:rgb(245, 37, 6);background:rgba(251, 251, 251, 0.78);">{{item.content}}</p>
						</div>
					</div>
				</div>
				<div class="viewswitch">
					<span @click="viewswitch"><img src="../assets/images/qiehuanjintou.png"></span>
				</div>
				<div class="sound-btn" :class=" isPaused ? 'addsound' : ''" @click="playPause()">
					<audio src="../static/mp3/wwj-bg1.mp3" autoplay="autoplay" preload="" loop="loop" id="bgmusic"></audio>
				</div>
				<div class="gamestarting" :class=" isNowgame ? 'none' : '' ">游戏正在开始中...</div>
				<div class="video">
					<canvas id="video-canvas" style="width:96%;height:100%;margin:0 auto;" width="500" height="500"></canvas>
				</div>
				<div class="flymsg">
				</div>
			</div>
			<div class="showCtrl">
				<div class="show_ctrlbox">
					<div class="show_ctrls" :class="isShowCtrl ? 'none' : ''">
						<div class="ctrl" style="text-align:right;">
							<router-link :to="{path:'/Userecord',query:{uid:this.$store.state.userInfo.uid}}" class="userrecordto is_loginbtn" style="background: transparent;display:inline-block;"><img src="../assets/images/shijian.png"></router-link>
						</div>
						<div>
							<a class="ctrlstatr" :class=" !istart ? 'dstartBg':'' " @click="ctrlStatr($event)">
							<div class="ctrlstatr_money">
								<img src="../assets/images/money.png"><span class="price">{{toyInfo.price}}/次</span>
							</div>
							</a>
						</div>
						<div class="ctrl" style="text-align:left;">
							<button id="chatbtn" class="is_loginbtn" style="background: transparent;" @click="chatBtn"><img src="../assets/images/liaotian.png"></button>
							<router-link class="mymoney is_loginbtn" to="/Recharge">{{coinbalance}}</router-link>
						</div>
					</div>
					<div class="show_ctrlsed" :class="!isShowCtrl ? 'none' : ''">
						<label class="downtime">{{isendtime ? downtime + "'" : ''}}</label>
						<div class="direction">
							<button class="left" @click="leftFn($event)"></button>
							<button class="up" @click="upFn($event)"></button>
							<button class="right" @click="rightFn($event)"></button>
							<button class="down" @click="downFn($event)"></button>
						</div>
						<div class="go">
							<button class="catch" @click="catchFn($event)"></button>
						</div>
					</div>
				</div>
			</div>
		</div>
		<chat-input v-on:listentChatmsg="showChatmsg" v-on:listentChatinput="showInputbox" v-on:listenprompt="listenpromptFn" v-on:listentOnline="onlineUser" v-show="showInput" :focus="isfocus"></chat-input>
		<app-prompt v-on:listentPromptanimt="Promptanimt" :content="Busymsg" :show="promptShow" ></app-prompt>
		<show-history v-on:listenToy="getToy"></show-history>
		<show-alert v-show="showAlert" :intro="alertIntro" v-on:listenShowalert="ShowalertFn"></show-alert>
		<div class="buzouimg" v-if="isnew" v-on:click.stop="hideBuzou"><img src="../assets/images/buzou2.png" style="width: 100%;"></div>
	</div>
</template>

<script type="text/javascript">
	import backHeader from '../components/backHeader'
	import chatInput from '../components/chatInput'
	import appPrompt from '../components/Prompt'
	import showAlert from '../components/showAlert'
	import showHistory from '../components/showHistory'
	import JSMpeg from '../../static/js/jsmpeg.js';
	let player;
	let socket;
	export default{
		name:"show",
		components:{backHeader,chatInput,appPrompt,showHistory,showAlert},
		data(){
			return {
				firstLogin:false,//判断用户登录
				coinbalance:0,
				times:null,//游戏开始倒计时
				downtime:30,//s
				isendtime:false,//倒计时是否结束
				istart:true,//true 可开始游戏 flase有人在玩
				isShowCtrl:false,//显示游戏操作 
				Busymsg:'',
				direction:true,//切换视角
				isNowgame:true,//点击开始游戏状态
				coinbalance:0,
				showInput:false,//显示聊天input
				chatMsg:[],//聊天消息
				isfocus:false,//点击按钮获取焦点
				promptShow:false,//显示提示框	
				onlineNum:0,//房间在线人数
				onnlineList:[],//在线用户列表
				showAlert:false,//显示输赢弹窗
				alertIntro:"",//输赢弹窗介绍
				toyInfo:"",//房间信息
				refereeInfo:"",//邀请好友介绍
				isPaused:true,
				isnew:false,
			}
		},
		mounted(){
			this.canvasJsmpeg();
			this._initConnect();
			this.referee();
			this.coinbalance = this.$store.state.userInfo.coinbalance;
			this.isnew = this.$store.getters.getNew;
		},
		beforeDestroy(){
			socket.close();
		},
		watch:{
			chatMsg(){
				this.$nextTick(() => {
					var container = this.$el.querySelector("#upchat_hall");
					container.scrollTop = container.scrollHeight;
				})
			}
		},
		methods:{
			hideBuzou(){
				this.isnew = false
				setTimeout(()=>{
					this.$store.commit("getRegister",this.isnew)
				},500)
			},
			playPause(){
				var myAudio = document.getElementById('bgmusic');
				if(myAudio.paused){
		            myAudio.play();
		            this.isPaused = true;
		        }else{
		            myAudio.pause();
		            this.isPaused = false;
		        }
			},
			goUserecord(touid){
				this.$router.push({path:'/Userecord',query:{uid:touid}});
			},
			showChatmsg(data){//监听其他用户的消息

				this.chatMsg.push(data);
				console.log(this.chatMsg);
			},
			showInputbox(data){//监听隐藏聊天input
				this.isfocus = false;
				this.showInput = data;
			},
			listenpromptFn(data){//监听显示报错提示框
				this.Busymsg = data;
				this.promptShow = true;
			},
			Promptanimt(data){//移除提示框
				this.promptShow = false;
			},
			getToy(data){
				this.toyInfo = data;
			},
			referee(){
				this.$jsonp(`${this.URL_PREFIX}/OpenAPI/v1/app/referee`,{token:this.$store.state.userInfo.token}).then((response) => {
		              console.log(response)
		              this.refereeInfo = response.data;
		  		 })
			},
			ShowalertFn(data){
				 this.showAlert =data;
			},
			canvasJsmpeg(){
				var canvas = document.getElementById('video-canvas');
				var url = 'wss://video.mxzhuawawa.com:8778';
				var stream1 = this.$route.query.roomid + "_1";
				var stream2 = this.$route.query.roomid + "_2";
				player = new JSMpeg.Jsm.Player(url, {canvas: canvas,"streams":[stream1,stream2],poster:"../assets/images/bg.jpg"});
			},
			chatBtn(){//显示消息窗口，自动获取焦点
				this.showInput = true;
				this.isfocus = true;

			},
			viewswitch(){
				player.source.switch();
				this.direction=!this.direction;
			},
			onlineUser(data){//获取在线用户
				this.onlineNum = data.all_num;
				this.onnlineList = data.client_list;
			},
			toUserecord(uid){
				this.$router.push({path:'/Userecord',})
			},
			_initConnect(){//连接socket
				var self=this;
				console.log('正在建立连接...');
		        try{
		            socket  =  new WebSocket('wss://catchtoy.mxzhuawawa.com:9979');
		        }catch(e){
		            console.log('连接异常 ： '+e);
		            return;
		        }
		        this._wbSocket = socket;
		        socket.onopen = (event) => {
		            if(!this.firstLogin){
		                if(this.$store.state.isLogin) {
		                    var data={};
		                    data.cmd = "login";
		                    data.uid = this.$store.state.userInfo.uid;
		                    data.machine_id =this.$route.query.roomid;
		                    data.sign =this.$store.state.userInfo.token;
		                    this._sendMsg(JSON.stringify(data));
		                    this.firstLogin = true;
		                }
		            }
		            socket.onmessage = this._msgReceive;

		            socket.onclose = (event) => {
		                console.log('连接关闭.',event);
		                this.firstLogin = false;
		            };
		        };
			},
			_sendMsg(msgBuf){
		        if(msgBuf!=null&&msgBuf!='undefined'){
		            this._wbSocket.send(msgBuf);
		        }else{
		            console.log('发送消息为空!');
		        }
		    },

		    _msgReceive(event) {
		        var data = JSON.parse(event.data);
		        console.log(data);
		        if(this.hasOwnProperty('_'+data.cmd)){
		            eval('this._'+data.cmd + '(data)');
		        }
		    },
		    _game_state(msg){
		    	msg.data == '1' ? this.istart = true : this.istart = false;
		    },
		    _start_game(msg){
		    	this.isendtime = true;
		    	this.isShowCtrl = true;
		        this.times=setInterval(() =>{
		            this.downtime--;
		            if(this.downtime==0){
		                this.downtime=30;
		                this.isendtime = false;
		                clearInterval(this.times);
		            }
		        },1000)
		        this.isNowgame  = true;
		        this.coinbalance = parseInt(msg.coinbalance);
		        this.$store.state.userInfo.coinbalance = parseInt(msg.coinbalance);
		    },	
		    _game_result(msg){
		    	console.log(msg)
		    	clearInterval(this.times);
		    	this.isShowCtrl =false;
		    	this.isendtime = false;
		    	this.downtime=30;
		    	if(this.$store.state.userInfo.coinbalance < this.toyInfo.price){
		    		if(msg.data == "0"){
		    			this.alertIntro={
		    				text1:"别灰心啦，小梦发现您只有"+this.$store.state.userInfo.coinbalance+"金币<br>已经不能抓啦，赶紧去充值吧！",
		    				text2:"邀请好友您将获得"+this.refereeInfo.referee_value+"金币的奖励哦",
		    				btn1:"邀请好友",
		    				btn2:"立即充值",
		    			}
		    		}else{
		    			this.alertIntro={
		    				text1:"恭喜您抓住啦一个"+this.toyInfo.title+"小梦发现您只有"+this.$store.state.userInfo.coinbalance+"金币<br>已经不能抓啦，赶紧去充值吧！",
		    				text2:"感紧把您的喜悦分享给您的好友啦<br>让他们来跟您一起享受抓娃娃的乐趣吧！",
		    				btn1:"立即分享",
		    				btn2:"立即充值",
		    			}
		    		}
		    	}else{
		    		if(msg.data == "0"){
		    			this.alertIntro={
		    				text1:"别灰心啦，小梦发现您还有"+this.$store.state.userInfo.coinbalance+"金币<br>还可以再抓取哦！",
		    				text2:"邀请好友您将获得"+this.refereeInfo.referee_value+"金币的奖励哦",
		    				btn1:"邀请好友",
		    				btn2:"立即重试",
		    			}
		    		}else{
		    			this.alertIntro={
		    				text1:"恭喜您抓住啦一个"+this.toyInfo.title+"小梦已经给您放到您的背包啦！",
		    				text2:"感觉把您的喜悦分享给您的好友啦<br>让他们来跟您一起享受抓娃娃的乐趣吧！",
		    				btn1:"立即分享",
		    				btn2:"再抓一次",
		    			}
		    		}
		    	}
		    	this.showAlert = true;
		    },
			ctrlStatr(event){//开始游戏
				console.log(event)
				if(this.istart){
					this.isNowgame  = false;
					var data={};
	                data.cmd = "start_game";
					this._sendMsg(JSON.stringify(data));
				}else{
					this.Busymsg = "当前房间已经有人在玩啦";
					this.promptShow = true;
				}
			},
			leftFn(event){
				this.direction?this.move(2):this.move(0);
			},
			upFn(event){
				this.direction?this.move(1):this.move(2);
			},
			rightFn(event){
				this.direction?this.move(3):this.move(1);
			},
			downFn(event){
				this.direction?this.move(0):this.move(3);
			},
			catchFn(event){
				var data={};
                data.cmd = "catch";
				this._sendMsg(JSON.stringify(data));
			},
			move(index){
				var data={};
                data.cmd = "move";
				data.direction =""+index+"";
				this._sendMsg(JSON.stringify(data));
			}
		}
	}
</script>
<style lang="less" scoped>
	@import '../assets/css/variables.less';
	#show{
		width:100%;
		height:100%;
		overflow-y: auto;
	}
	.buzouimg{
		width:100%;
		height:100%;
		position: fixed;
		top:0;
		left: 0;
		z-index: 1111;
	}
	.catchblock {
	    width: 100%;
	    height: 100%;
	    background: @yellowLight;
	    overflow-x:hidden;
	}
	.show_video {
	    width: 95%;
	    height: -webkit-calc(100% - 165px);
	    height: calc(100% - 165px);
	    margin: 0 auto;
	    background: url(../assets/images/biankuang.png) no-repeat top center;
	    background-size: cover;
	    border-radius: 5px;
	    overflow: hidden;
	    position: relative
	}
	.onlines {
	    position: absolute;
	    top: 10px;
	    right: 0.66rem;
	    z-index: 2;
	    max-width: 80%;
	    text-align: right;
	    .onlinenum {
		    display: inline-block;
		    color: #fff;
		    background: rgba(0,0,0,0.5);
		    border-radius: 20px;
		    padding: 2px 10px;
		    font-size: 12px;
		    margin: 5px;
		}

		.onlinenum span {
		    display: block;
		    width: 100%;
		    font-size: 14px
		}
	}
	.onlineuser {
	    width: 100%;
	    text-align: right;
	    padding: 0 5px;
	    overflow-x: auto;
	    font-size: 0;
	    li {
		    display: inline-block;
		    width: 30px;
		    height: 30px;
		    border-radius: 50%;
		    margin-right: 2px;
		    cursor: pointer;
		}
		img {
		    width: 30px;
		    height: 30px;
		    border-radius: 50%;
		}
	}
	.chat-msg-box {
	    width: 100%;
	    height: 45px;
	    position: absolute;
	    bottom: 0.6rem;
	    left: 0;
	    font-size: 0;
	    overflow: hidden;
	    overflow-y: auto;
	    .live-msg-list {
		    padding: 0 12px;
		    .msg {
			    margin: 6px 0;
			}
			.msg span {
			    color: #f89c03;
			    font-size: 12px;
			}
			.msg p {
			    color: #fff;
			    display: inline-block;
			    font-size: 12px;
			    padding: 0 10px;
			    border-radius: 20px;
			}
		}

	}
	.viewswitch {
	    position: absolute;
	    right: 0;
	    top: 160px;
	    width: 60px;
	    height: 49px;
	    background: #fff6cb;
	    border-radius: 25px 0 0 25px;
	    span {
		    display: inline-block;
		    border-radius: 50%;
		    width: 45px;
		    height: 45px;
		    margin: 2px 5px;
		}
		span img {
		    width: 45px;
		}
	}
	.sound-btn {
	    width: 30px;
	    height: 30px;
	    display: block;
	    background: url(../assets/images/bgmusic.png) no-repeat center;
	    background-size: cover;
	    border-radius: 50%;
	    position: absolute;
	    right: 1rem;
	    top: 80px;
	}
	.catchblock .addsound {
	    -webkit-animation: spin 1s infinite linear;
	    animation: spin 1s infinite linear
	}

	@-webkit-keyframes spin {
	    0% {
	        -webkit-transform: rotate(0deg);
	        transform: rotate(0deg)
	    }

	    to {
	        -webkit-transform: rotate(1turn);
	        transform: rotate(1turn)
	    }
	}

	@keyframes spin {
	    0% {
	        -webkit-transform: rotate(0deg);
	        transform: rotate(0deg)
	    }

	    to {
	        -webkit-transform: rotate(1turn);
	        transform: rotate(1turn)
	    }
	}
	.gamestarting {
	    position: absolute;
	    top: 40%;
	    left: 50%;
	    margin-left: -60px;
	    width: 120px;
	    height: 60px;
	    line-height: 60px;
	    color: #fff;
	    text-align: center;
	    background: rgba(0,0,0,0.6);
	    border-radius: 6px;
	    font-size: 14px;
	}
	.video {
	    width: 100%;
	    height: 100%;
	    padding: 2.5% 0;
	}
	.flymsg {
	    width: 100%;
	    position: absolute;
	    top: 0;
	    left: 0;
	    z-index: 0;
	    .msgitem {
		    position: absolute;
		    top: 0;
		    left: 0;
		    border-radius: 20px;
		    font-size: 0;
		    padding-right: 5px;
		    width: 100%;
		}
		.msgitem img {
		    width: 30px;
		    height: 30px;
		    border-radius: 50%;
		    vertical-align: middle;
		}
		.msgitem span {
		    color: #f59a13;
		    font-size: 16px;
		    vertical-align: middle;
		    font-weight: 600;
		}
	}

	.show_ctrlbox {
	    margin-top: 5px;
	    background: url(../assets/images/showplaybg.jpg) no-repeat center;
	    background-size: cover;
	}
	.show_ctrls {
	    width: 95%;
	    margin: 0 auto;
	    display: -webkit-flex;
	    display: flex;
	    flex-direction: row;
	    padding: 20px 0 50px;
	}
	.show_ctrls.none {
	    display: none;
	}
	.show_ctrls > div {
	    flex-grow: 1;
	    text-align: center
	}
	.show_ctrls .ctrl {
	    position: relative
	}

	.show_ctrls .ctrl img {
	    width: 60px;
	    margin-top: 15px
	}

	.show_ctrls .ctrl .mymoney {
	    display: block;
	    padding: 0 35px 0 25px;
	    min-width: 60px;
	    height: 25px;
	    line-height: 25px;
	    position: absolute;
	    bottom: -30px;
	    right: -10px;
	    background: #c48305;
	    border-radius: 20px 0 0 20px;
	    font-size: 12px;
	    color: #fff;
	}

	.show_ctrls .ctrl .mymoney:before {
	    display: block;
	    content: "";
	    width: 20px;
	    height: 20px;
	    background: url(../assets/images/chongzhizhongxinjinbi.png) no-repeat center;
	    background-size: 15px;
	    position: absolute;
	    top: 2px;
	    left: 0
	}
	.show_ctrls .ctrl .mymoney:after {
	    display: block;
	    content: "";
	    width: 20px;
	    height: 20px;
	    background: url(../assets/images/add_add.jpg) no-repeat center;
	    background-size: 15px;
	    position: absolute;
	    top: 2px;
	    right: 10px
	}

	.show_ctrls .ctrl .mymoney img {
	    width: 15px;
	    vertical-align: middle
	}

	.show_ctrls .ctrlstatr {
	    display: block;
	    width: 160px;
	    height: 95px;
	    margin: 0 auto;
	    background-image: url(../assets/images/kaishizhuawawa.png);
	    background-size: 100%;
	    background-repeat: no-repeat;
	    font-size: 14px;
	    color: #fff;
	}
	.show_ctrls .ctrlstatr.dstartBg {
	    background-image: url(../assets/images/qitayouxizhong.png);
	}

	.show_ctrls .ctrlstatr .ctrlstatr_money {
	    padding-top: 42px;
	    font-size: 16px;
	}

	.show_ctrls .ctrlstatr > span {
	    display: block;
	    padding: 6px 0 5px
	}

	.show_ctrls .ctrlstatr img {
	    width: 15px;
	    margin-right: 3px
	}

	.ctrlstatr_money img {
	    vertical-align: middle
	}

	.show_ctrlsed {
	    position: relative;
	    width: 95%;
	    height: 160px;
	    margin: 0 auto;
	    padding: 15px 0
	}
	.show_ctrlsed.none {
	    display: none;
	}

	.show_ctrlsed button {
	    position: absolute
	}
	.direction {
	    height: 130px;
	    width: 180px;
	    position: relative;
	    float: left;
	}

	.direction button {
	    width: 60px;
	    height: 60px;
	    display: block;
	}

	.direction .left {
	    left: 0px;
	    top: 45%;
	    margin-top: -25px;
	    background: url(../assets/images/zuoyijian.png) no-repeat center;
	    background-size: cover;
	    transition: all 0.3s linear;
	    -webkit-transition: all 0.3s linear;
	}

	.direction .up {
	    top: 0;
	    left: 50%;
	    margin-left: -28px;
	    background: url(../assets/images/shangyijian.png) no-repeat center;
	    background-size: cover;
	    transition: all 0.3s linear;
	    -webkit-transition: all 0.3s linear;
	}
	.direction .right {
	    right: 0px;
	    top: 45%;
	    margin-top: -25px;
	    background: url(../assets/images/youyijian.png) no-repeat center;
	    background-size: cover;
	    transition: all 0.3s linear;
	    -webkit-transition: all 0.3s linear;
	}

	.direction .down {
	    bottom: 0;
	    left: 50%;
	    margin-left: -30px;
	    background: url(../assets/images/xiayijian.png) no-repeat center;
	    background-size: cover;
	    transition: all 0.3s linear;
	    -webkit-transition: all 0.3s linear;
	}

	.direction .left:active {
	    left: 0px;
	    top: 45%;
	    margin-top: -25px;
	    background: url(../assets/images/zuoyijian.png) no-repeat center;
	    background-size: 90%;
	}

	.direction .up:active {
	    top: 0;
	    left: 50%;
	    margin-left: -28px;
	    background: url(../assets/images/shangyijian.png) no-repeat center;
	    background-size: 90%;
	}

	.direction .right:active {
	    right: 0px;
	    top: 45%;
	    margin-top: -25px;
	    background: url(../assets/images/youyijian.png) no-repeat center;
	    background-size: 90%;
	}
	.direction .down:active {
	    bottom: 0;
	    left: 50%;
	    margin-left: -30px;
	    background: url(../assets/images/xiayijian.png) no-repeat center;
	    background-size: 90%;
	}

	.go {
	    position: relative;
	    float: right;
	    padding-top: 1.5rem;
	    padding-right: 2rem;
	}

	.go .catch {
	    width: 87px;
	    height: 85px;
	    position: relative;
	    left: 0;
	    top: 20%;
	    background: url(../assets/images/kaishiyouxi.png) no-repeat center;
	    background-size: cover;
	    transition: all 0.3s linear;
	    -webkit-transition: all 0.3s linear;
	}

	.go .catch:active {
	    width: 87px;
	    height: 85px;
	    left: 0;
	    top: 20%;
	    background: url(../assets/images/kaishiyouxi.png) no-repeat center;
	    background-size: 95%;
	}

	.downtime {
	    position: absolute;
	    top: 10px;
	    right: 0;
	    color: #fb371c;
	    font-size: 18px;
	}













</style>